package com.itheima.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request =  (HttpServletRequest)servletRequest;
        // 获取请求的url
        String requestURI = request.getRequestURI();  //   /login.html
        // 判断url是否是login.html，如果是，则放行
        if("/login.html".equals(requestURI) || "/user/login.do".equals(requestURI) || requestURI.contains("css") || requestURI.contains("plugins") || requestURI.contains("js") || requestURI.contains("img") || requestURI.contains("favicon")){
            filterChain.doFilter(servletRequest,servletResponse);
        } else{
            //1. 反之则从session中取出用户名
            HttpSession session = request.getSession();
            String username =  (String)session.getAttribute("username");
            if(username != null){
                //2. 如果username不为null，则表示这个人登陆过,放行
                filterChain.doFilter(servletRequest,servletResponse);
            }else{
                //3. 如果username为null，则表示这个人没登陆过，则重定向到登录页面
                HttpServletResponse response =  (HttpServletResponse)servletResponse;
                response.sendRedirect("/login.html");
            }
        }
    }

    @Override
    public void destroy() {

    }
}
